package com.eqdd.yiqidian.ui.select;

import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;

import com.eqdd.yiqidian.ListItem95Custom;
import com.eqdd.yiqidian.R;
import com.eqdd.yiqidian.RecyclerViewCustom;
import com.eqdd.yiqidian.adapter.slimadapter.SlimAdapterEx;
import com.eqdd.yiqidian.adapter.slimadapter.SlimInjector;
import com.eqdd.yiqidian.adapter.slimadapter.viewinjector.IViewInjector;
import com.eqdd.yiqidian.base.BaseActivity;
import com.eqdd.yiqidian.base.Config;
import com.eqdd.yiqidian.bean.rebuild.OptionBean;
import com.eqdd.yiqidian.http.DialogCallBack;
import com.eqdd.yiqidian.http.HttpConfig;
import com.eqdd.yiqidian.utils.ToastUtil;
import com.example.library.AutoFlowLayout;
import com.example.library.FlowAdapter;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.model.Response;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Flowable;

/**
 * @author吕志豪 .
 * @date 18-1-5  上午11:50.
 * Github :https://github.com/lvzhihao100
 * E-Mail：1030753080@qq.com
 * 简书 :http://www.jianshu.com/u/6e525b929aac
 */

public class SelectTwoDeepMultiTagActivity extends BaseActivity {
    private List<SelectTextMultiActivity.TagBean> results = new ArrayList<>();

    private RecyclerViewCustom dataBinding;
    private int option;
    private SlimAdapterEx slimAdapterEx;
    private int maxNum;
    private String[] split;

    @Override
    public void initBinding() {
        dataBinding = DataBindingUtil.setContentView(this, R.layout.activity_recyclerview);
        initTopTitleBar(View.VISIBLE, "讲师/课程/培训分类");
        initTopRightText("确定", v -> {
            if (results.size() > 0) {
                Intent intent = new Intent();
                ArrayList<String> strResults = new ArrayList<>();
                Flowable.fromIterable(results)
                        .subscribe(o -> strResults.add(o.text));
                intent.putStringArrayListExtra(Config.STRING_LIST, strResults);
                setResult(Config.SUCCESS, intent);
                finish();
            } else {
                ToastUtil.showShort("至少选一个");
            }
        });
    }

    @Override
    public void initData() {
        option = getIntent().getIntExtra(Config.OPTION, 0);
        maxNum = getIntent().getIntExtra(Config.MAX_NUM, 0);
        String selectString = getIntent().getStringExtra(Config.STRING_LIST);
        if (selectString != null) {
            split = selectString.split(",");
        }
        dataBinding.recyclerView.setLayoutManager(new LinearLayoutManager(this));
        slimAdapterEx = SlimAdapterEx.create().register(R.layout.list_item_96, new SlimInjector<Options>() {
            @Override
            public void onInject(Options data, IViewInjector injector) {
                injector.text(R.id.tv_title, data.getName());
//                        .with(R.id.recyclerView, view -> {
//                            RecyclerView recyclerView = (RecyclerView) view;
//                            recyclerView.setLayoutManager(new FlowLayoutManager());
//                            SlimAdapterEx<SelectTextMultiActivity.TagBean> slimAdapterExTag =
//                                    SlimAdapterEx.create().register(R.layout.list_item_95, new SlimInjector<SelectTextMultiActivity.TagBean>() {
//                                        @Override
//                                        public void onInject(SelectTextMultiActivity.TagBean data, IViewInjector injector) {
//                                            injector.text(R.id.bt_tag, data.text)
//                                                    .background(R.id.bt_tag, data.isCheck ?
//                                                            getResources().getDrawable(R.drawable.shape_17_tag_selected) :
//                                                            getResources().getDrawable(R.drawable.shape_17_tag_unselected));
//                                        }
//                                    }).attachTo(recyclerView).updateData(new ArrayList());
//                            slimAdapterExTag.getData().addAll(data.getTagBeans());
//                            slimAdapterExTag.notifyItemRangeInserted(0, data.getTagBeans().size());
//                            ItemClickSupport.addTo(recyclerView)
//                                    .setOnItemClickListener((recyclerView1, position, v) -> {
//                                        slimAdapterExTag.getDataItem(position).isCheck = !slimAdapterExTag.getDataItem(position).isCheck;
//                                        if (slimAdapterExTag.getDataItem(position).isCheck) {
//                                            results.add(slimAdapterExTag.getDataItem(position));
//                                        } else {
//                                            results.remove(slimAdapterExTag.getDataItem(position));
//                                        }
//                                        if (results.size() == maxNum + 1) {
//                                            ToastUtil.showShort("最多选" + maxNum + "个");
//                                            slimAdapterExTag.getDataItem(position).isCheck = !slimAdapterExTag.getDataItem(position).isCheck;
//                                            results.remove(slimAdapterExTag.getDataItem(position));
//
//                                        } else {
//                                            slimAdapterExTag.notifyItemChanged(position);
//                                        }
//                                    });
//                        });
                AutoFlowLayout<SelectTextMultiActivity.TagBean> mFlowLayout = (AutoFlowLayout) injector.findViewById(R.id.autoFlowLayout);
                mFlowLayout.clearViews();
                FlowAdapter<SelectTextMultiActivity.TagBean> flowAdapter = new FlowAdapter<SelectTextMultiActivity.TagBean>(data.getTagBeans()) {
                    @Override
                    public View getView(int position) {
                        ListItem95Custom inflate = DataBindingUtil.inflate(getLayoutInflater(), R.layout.list_item_95, null, false);
                        inflate.btTag.setText(getItem(position).text);
                        inflate.btTag.setBackground(getItem(position).isCheck ?
                                getResources().getDrawable(R.drawable.shape_17_tag_selected_1) :
                                getResources().getDrawable(R.drawable.shape_17_tag_unselected_1));
                        return inflate.getRoot();
                    }
                };
                mFlowLayout.setAdapter(flowAdapter);
                mFlowLayout.setOnItemClickListener((position, view) -> {
                    flowAdapter.getItem(position).isCheck = !flowAdapter.getItem(position).isCheck;
                    if (flowAdapter.getItem(position).isCheck) {
                        results.add(flowAdapter.getItem(position));
                    } else {
                        results.remove(flowAdapter.getItem(position));
                    }
                    if (results.size() == maxNum + 1) {
                        ToastUtil.showShort("最多选" + maxNum + "个");
                        flowAdapter.getItem(position).isCheck = !flowAdapter.getItem(position).isCheck;
                        results.remove(flowAdapter.getItem(position));
                    } else {
                        mFlowLayout.deleteView(position);
                        mFlowLayout.addView(flowAdapter.getView(position), position);
                        mFlowLayout.requestLayout();
                    }
                });
                mFlowLayout.setVerticalSpace(200);
                mFlowLayout.setHorizontalSpace(200);


            }
        }).attachTo(dataBinding.recyclerView).updateData(new ArrayList());

    }

    @Override
    public void setView() {
        OkGo.<List<OptionBean>>get(HttpConfig.BASE_URL + HttpConfig.AREA_OPTIONS)
                .params("type", option)
                .cacheMode(CacheMode.IF_NONE_CACHE_REQUEST)
                .cacheKey(HttpConfig.BASE_URL + HttpConfig.AREA_OPTIONS + option)
                .execute(new DialogCallBack<List<OptionBean>>(this) {
                    @Override
                    public void onSuccess(Response<List<OptionBean>> response) {
                        loadNetData(response);

                    }

                    @Override
                    public void onCacheSuccess(Response<List<OptionBean>> response) {
                        super.onCacheSuccess(response);
                        loadNetData(response);

                    }

                    @Override
                    public void onError(Response<List<OptionBean>> response) {
                        super.onError(response);
                        ToastUtil.showShort("数据获取失败，请稍候重试");
                    }
                });
    }

    private void loadNetData(Response<List<OptionBean>> response) {
        List<OptionBean> optionBean = response.body();
        ArrayList<Options> options = new ArrayList<>();
        Flowable.fromIterable(optionBean)
                .subscribe(bean -> {
                    Options options1 = new Options();
                    options1.setName(bean.getName());
                    options1.setTagBeans(new ArrayList<SelectTextMultiActivity.TagBean>());
                    Flowable.fromIterable(bean.getSub())
                            .subscribe(o -> {
                                if (split != null) {
                                    boolean isCheck = false;
                                    for (String s : split) {
                                        if (o.getName().equals(s)) {
                                            SelectTextMultiActivity.TagBean tagBean = new SelectTextMultiActivity.TagBean(o.getName(), true);
                                            options1.getTagBeans().add(tagBean);
                                            results.add(tagBean);
                                            isCheck = true;
                                            break;
                                        }
                                    }
                                    if (!isCheck) {
                                        options1.getTagBeans().add(new SelectTextMultiActivity.TagBean(o.getName()));
                                    }
                                } else {
                                    options1.getTagBeans().add(new SelectTextMultiActivity.TagBean(o.getName()));
                                }
                            });
                    options.add(options1);
                });
        slimAdapterEx.updateData(options);
    }

    class Options {
        String name;
        List<SelectTextMultiActivity.TagBean> tagBeans;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public List<SelectTextMultiActivity.TagBean> getTagBeans() {
            return tagBeans;
        }

        public void setTagBeans(List<SelectTextMultiActivity.TagBean> tagBeans) {
            this.tagBeans = tagBeans;
        }
    }
}
